package cn.nfwx.tv.fragment.search;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import com.yqritc.recyclerviewflexibledivider.VerticalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.nfwx.tv.R;
import cn.nfwx.tv.adapter.SearchHistoryAdapter;
import cn.nfwx.tv.adapter.SearchHotAdapter;
import cn.nfwx.tv.base.BaseDialogFragment;
import cn.nfwx.tv.callback.ResponseListener;
import cn.nfwx.tv.controller.SearchResultViewController;
import cn.nfwx.tv.events.PlayEvents;
import cn.nfwx.tv.events.QpopPlayEvent;
import cn.nfwx.tv.fragment.callback.ActionCallback;
import cn.nfwx.tv.helper.ThreadHelper;
import cn.nfwx.tv.manager.SearchManager;
import cn.nfwx.tv.model.Result;
import cn.nfwx.tv.model.TilteModel;
import cn.nfwx.tv.model.TvProgram;
import cn.nfwx.tv.util.SharePrefUtil;
import cn.nfwx.tv.widget.LoadView;

public class SearchFragment extends BaseDialogFragment implements View.OnClickListener, BaseQuickAdapter.OnItemClickListener, ResponseListener<JSONObject> {

    LinearLayout search_main_rel;
    EditText et_keyword;
    RecyclerView search_history_recyclerView;
    FrameLayout fl_content;
    ListView search_hot_listView;
    ImageView search_back_btn, search_edit_btn;

    SearchHotAdapter hotAdapter;
    SearchHistoryAdapter searchHistoryAdapter;

    LoadView loadView;

    SearchResultViewController searchResultViewController;
    //SearchResultSubController searchResultSubController;
    InputMethodManager imm;

    String requestIjkHotKeywordCommad;
    boolean isReShow = false;
    public boolean isBackEvent = true;
    String keyword;

    public final static String ACTION_SEARCH_DIMISS = "ACTION_SEARCH_DIMISS";
    private ActionCallback mActionCallback;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActionCallback = ActionCallback.NONE;
        if (activity instanceof ActionCallback) {
            mActionCallback = (ActionCallback) activity;
        }
    }

    /**
     * =======http-callback=====
     *
     * @param requestTag
     * @param response
     */
    @Override
    public void onResponse(String requestTag, JSONObject response) {
        if (requestTag.equals(requestIjkHotKeywordCommad)) {
            String message = response.toString();
            Result<List<String>> result = JSON.parseObject(message, new TypeReference<Result<List<String>>>() {
            }.getType());
            if (result.getMessage().equals(Result.RESULT_SUCCESS)) {
                final List<String> datas = result.getData();
                ThreadHelper.post(new Runnable() {
                    @Override
                    public void run() {
                        hotAdapter.setNewData(datas);
                        if (loadView.getParent() != null) {
                            fl_content.removeView(loadView);
                        }
                    }
                });
            }
        }
    }

    @Override
    public void onError(String requestTag, Throwable t) {

    }

    @Override
    public void onFinish() {

    }

    /**
     * =======
     */

    public interface OnEventListener {
        void dimiss();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        if (mActionCallback != null) {
            if (isBackEvent) {
                mActionCallback.callbackByfragment(ACTION_SEARCH_DIMISS, null);
            } else {
                isBackEvent = true;
            }
        }
        super.onDismiss(dialog);
    }

    public static SearchFragment newInstance() {
        SearchFragment fragment = new SearchFragment();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);

        Bundle bundle = getArguments();
        if (bundle != null) {
            String keyword = bundle.getString("keyword");
            if (!TextUtils.isEmpty(keyword)) {
                isReShow = true;
                this.keyword = keyword;
            }
        }

        searchResultViewController = new SearchResultViewController(this);
        getLifecycle().addObserver(searchResultViewController);
        //searchResultSubController = new SearchResultSubController(this);
        search_main_rel = findView(R.id.search_main_rel);
        et_keyword = findView(R.id.et_keyword);
        search_history_recyclerView = findView(R.id.search_history_recyclerView);
        fl_content = findView(R.id.fl_content);
        search_hot_listView = findView(R.id.search_hot_listView);
        search_back_btn = findView(R.id.search_back_btn);
        search_edit_btn = findView(R.id.search_edit_btn);
        findView(R.id.iv_clear_history).setOnClickListener(this);
        findView(R.id.ll_content).setOnClickListener(this);
        findView(R.id.ll_content).requestFocus();
        hotAdapter = new SearchHotAdapter(getContext());
        search_hot_listView.setAdapter(hotAdapter);
        search_back_btn.setOnClickListener(this);
        search_edit_btn.setOnClickListener(this);
        loadView = new LoadView(getContext());
        getLifecycle().addObserver(loadView);
        loadView.setOnLoadClickLisener(new LoadView.OnLoadClickListener() {
            @Override
            public void onreload() {
                initData();
            }

            @Override
            public void onnext() {

            }
        });

        FlexboxLayoutManager manager = new FlexboxLayoutManager();
        //设置主轴排列方式
        manager.setFlexDirection(FlexDirection.ROW);
        //设置是否换行
        manager.setFlexWrap(FlexWrap.WRAP);
        manager.setAlignItems(AlignItems.BASELINE);
        search_history_recyclerView.setLayoutManager(manager);
        search_history_recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getContext()).size(30).build());
        search_history_recyclerView.addItemDecoration(new VerticalDividerItemDecoration.Builder(getContext()).size(10).build());
        searchHistoryAdapter = new SearchHistoryAdapter(getActivity());
        search_history_recyclerView.setAdapter(searchHistoryAdapter);

        imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        initData();
        initListener();
        loadData();
    }

    /**
     * 加载
     */
    private void loadData() {
        if (isReShow) {
            isReShow = false;
            search_main_rel.setVisibility(View.GONE);
            et_keyword.setText(keyword);
            searchResultViewController.setDataIjkKeyword(keyword);
            searchResultViewController.show();
        }
    }

    private void initData() {
        ArrayList<String> keywords = SharePrefUtil.getSearchKeyWord(getActivity());
        if (keywords != null && !keywords.isEmpty()) {
            searchHistoryAdapter.setNewData(keywords);
        }


        requestIjkHotKeywordCommad = SearchManager.requestIjkHotKeyword(getContext(), this);
    }

    public void loadResultData(String keyword) {
        Bundle bundle = new Bundle();
        bundle.putString("keyword", keyword);
        this.setArguments(bundle);
    }

    private void initListener() {
        searchHistoryAdapter.setOnItemClickListener(new SearchHistoryAdapter.OnItemClickListener() {
            @Override
            public void itemClick(RecyclerView.Adapter adapter, View view, int position, String keyword) {
                search_main_rel.setVisibility(View.GONE);
                et_keyword.setText(keyword);
                searchResultViewController.setDataIjkKeyword(keyword);
                searchResultViewController.show();
                SharePrefUtil.saveSearchKeyWord(getActivity(), keyword);
                initData();
            }
        });

        hotAdapter.setOnItemClickListener(new SearchHotAdapter.OnItemClickListener() {
            @Override
            public void itemClick(View view, int position, String keyword) {
                search_main_rel.setVisibility(View.GONE);
                et_keyword.setText(keyword);
                searchResultViewController.setDataIjkKeyword(keyword);
                searchResultViewController.show();
                SharePrefUtil.saveSearchKeyWord(getActivity(), keyword);
                initData();
            }
        });

        et_keyword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    search_main_rel.setVisibility(View.GONE);
                    String keyword = et_keyword.getEditableText().toString();
                    et_keyword.setText(keyword);
                    searchResultViewController.setDataIjkKeyword(keyword);
                    searchResultViewController.show();
                    SharePrefUtil.saveSearchKeyWord(getActivity(), keyword);
                    initData();
                }
                return false;
            }
        });
    }

    /**
     * 是否填满整个屏幕
     */
    protected boolean isMatchParent() {
        return true;
    }

    protected boolean isOutsideTouchable() {
        return true;
    }

    //是否透明背景
    protected boolean isTranslucentBackground() {
        return false;
    }

    protected boolean isTranslucentStatus() {
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_back_btn:
//                if (searchResultSubController.isShow()) {
//                    searchResultSubController.hidden();
//                    searchResultViewController.show();
//                } else
                if (search_main_rel.getVisibility() == View.GONE) {
                    search_main_rel.setVisibility(View.VISIBLE);
                    searchResultViewController.hidden();
                    et_keyword.setText("");
                } else if (search_main_rel.getVisibility() == View.VISIBLE) {
                    dismiss();
                }
                break;
            case R.id.search_edit_btn:
                search_main_rel.setVisibility(View.GONE);
                String keyWord = et_keyword.getEditableText().toString();
                searchResultViewController.setDataIjkKeyword(keyWord);
                SharePrefUtil.saveSearchKeyWord(getContext(), keyWord);
                initData();
                searchResultViewController.show();
                if (imm != null) {
                    imm.hideSoftInputFromWindow(et_keyword.getWindowToken(), 0);
                }
                break;
            case R.id.iv_clear_history:
                Dialog dialog = getDialog(R.layout.dialog_sreach_delete);
                dialog.show();
                break;
            case R.id.ll_content:
                if (imm != null) {
                    imm.hideSoftInputFromWindow(et_keyword.getWindowToken(), 0);
                }
                break;
            case R.id.et_keyword:
                et_keyword.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI | EditorInfo.IME_FLAG_NO_FULLSCREEN);
                break;
        }
    }

    public Dialog getDialog(int resId) {
        final Dialog dialog = new Dialog(getContext(), R.style.MyDialog);
        View dialogView = View.inflate(getContext(), resId, null);
        TextView cancle_btn = dialogView.findViewById(R.id.btn_logout_cancle);
        TextView sure_btn = dialogView.findViewById(R.id.btn_logout_sure);
        sure_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.cancel();
                SharePrefUtil.clearSearchKeyWord(getContext());
                searchHistoryAdapter.clearData();
            }
        });
        cancle_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.cancel();
            }
        });
        dialog.setContentView(dialogView);
        Window dialogWindow = dialog.getWindow();
        WindowManager m = getActivity().getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.8); // 高度设置为屏幕的0.6，根据实际情况调整
        p.width = (int) (d.getWidth() * 0.6); // 宽度设置为屏幕的0.65，根据实际情况调整
        dialogWindow.setAttributes(p);
        return dialog;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void qpopPlayerEvent(QpopPlayEvent qpopPlayEvent) {
        dismiss();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        searchResultViewController.release();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (position < adapter.getData().size()) {
            if (adapter.getData().get(position) instanceof TilteModel) { // 加载，收起
                // 获取多余的部分
                List<Object> objects = searchResultViewController.getMoreList();
                TilteModel tilteModel = (TilteModel) adapter.getData().get(position);
                if (tilteModel.isLoadMore) {
                    for (int j = 0; j < objects.size(); j++) {
                        adapter.remove(position - 1 - j);
                    }
                    ((TextView) view).setText(R.string.load_more);
                    tilteModel.isLoadMore = false;
                } else {
                    adapter.addData(position, objects);
                    ((TextView) view).setText(R.string.ellipsis);
                    tilteModel.isLoadMore = true;
                }
            } else if (adapter.getData().get(position) instanceof TvProgram) {
                TvProgram tvProgram = (TvProgram) adapter.getData().get(position);
                if (!TextUtils.isEmpty(tvProgram.getUrl())) {
                    String keyword = et_keyword.getEditableText().toString();
                    isBackEvent = false;
                    PlayEvents events = new PlayEvents(tvProgram.getProgram_id(), tvProgram.getUrl(), null, tvProgram.getProgram_name(), 0);
                    events.setFragment(PlayEvents.SEARCH);
                    events.setKeyword(keyword);
                    events.setTag("search");
                    EventBus.getDefault().post(events);
                    dismissAllowingStateLoss();
                }
            }
        }
    }

//    /**
//     * 显示栏目详情
//     *
//     * @param subscriptionModel
//     */
//    public void showSubscriptionDetail(SubscriptionModel subscriptionModel) {
//        search_main_rel.setVisibility(View.GONE);
//        searchResultViewController.hidden();
//        searchResultSubController.show(subscriptionModel);
//    }
}
